package com.futvan.z.system.zhttpservices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.JavaClass;
import com.futvan.z.framework.common.bean.JavaMethod;
import com.futvan.z.framework.common.bean.JavaMethodParameter;
import com.futvan.z.framework.common.bean.JavaVariable;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.FileUtil;
import com.futvan.z.framework.util.JavaCompilerUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.framework.util.SystemUtil;
import com.futvan.z.system.zhttpservices.ZhttpservicesService;
@Controller
public class ZhttpservicesAction extends SuperAction{
	@Autowired
	private ZhttpservicesService zhttpservicesService;
	@Autowired
	private CommonService commonService;

	/**
	 * HTTP接口
	 * @param bean
	 * @return Result
	 * @throws Exception
	 * 
	 * serviceid 接口标识
	 * accesskeyid 密钥id
	 * accesskeysecret 密钥secret
	 */
	@RequestMapping(value="/httpservices")
	public @ResponseBody Result httpservices(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = new Result();
		String serviceid = bean.get("serviceid");
		if(z.isNotNull(serviceid)) {
			//验证访问权限
			Result authority = z.isServiceAuthority(bean,request);
			if(Code.SUCCESS.equals(authority.getCode())){
				//权限验证通过，调用接口
				result = RunService(bean);
			}else {
				result = authority;
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("serviceid is null");
		}
		return result;
	}

	/**
	 * 运行接口
	 * @param bean
	 * @return
	 */
	public Result RunService(HashMap<String, String> bean) {
		Result result = new Result();
		//获取接口对象
		z_http_services service = z.httpservices.get(bean.get("serviceid"));

		//SQL接口
		if("0".equals(service.getHttp_services_type())) {
			//查询
			if("0".equals(service.getHttp_services_operating_type())) {
				String sql = StringUtil.parseExpression(service.getSqlinfo(), bean);
				List<HashMap<String,String>> list = commonService.SelectForSQL(sql);
				result.setCode(Code.SUCCESS);
				result.setData(list);
			}
			//插入
			if("1".equals(service.getHttp_services_operating_type())) {
				String sql = StringUtil.parseExpression(service.getSqlinfo(), bean);
				int num = commonService.InsertForSQL(sql);
				result.setCode(Code.SUCCESS);
				result.setMsg("插入数据["+num+"]条");
				result.setData(num);
			}
			//修改
			if("2".equals(service.getHttp_services_operating_type())) {
				String sql = StringUtil.parseExpression(service.getSqlinfo(), bean);
				int num = commonService.UpdateForSQL(sql);
				result.setCode(Code.SUCCESS);
				result.setMsg("修改数据["+num+"]条");
				result.setData(num);
			}
			//删除
			if("3".equals(service.getHttp_services_operating_type())) {
				String sql = StringUtil.parseExpression(service.getSqlinfo(), bean);
				int num = commonService.DeleteForSQL(sql);
				result.setCode(Code.SUCCESS);
				result.setMsg("删除数据["+num+"]条");
				result.setData(num);
			}
		}

		//如果返回为空，设置通用错误提示
		if(z.isNull(result) || z.isNull(result.getCode())) {
			result.setCode(Code.ERROR);
			result.setMsg("未知错误 Result is null");
		}
		return result;
	}


	@RequestMapping(value="/z_http_services_insert")
	public @ResponseBody Result z_http_services_insert(@RequestParam HashMap<String,String> bean) throws Exception {
		//判读是否为自定义程序接口，并生成相应接口文件
		CreateHttpServiceFile(bean);
		return commonService.insert(bean, request);
	}



	@RequestMapping(value="/z_http_services_update")
	public @ResponseBody Result z_http_services_update(@RequestParam HashMap<String,String> bean) throws Exception {
		//判读是否为自定义程序接口，并生成相应接口文件
		CreateHttpServiceFile(bean);
		return commonService.update(bean, request);
	}

	/**
	 * 创建自定义接口文件
	 * @param bean
	 * @throws Exception
	 */
	private void CreateHttpServiceFile(HashMap<String, String> bean) throws Exception {
		//是否为自定义程序接口
		if("1".equals(bean.get("http_services_type"))) {
			String projectid = bean.get("projectid");//所属项目
			String serviceid = bean.get("serviceid");//接口标识

			/*
			 * 判读当前环境是否是Eclipse开发环境运行的， 如果是开发环境，自定义程序生成后台处理类，
			 * 如果是Tomcat环境，根据javainfo创建java处理类，并编译。
			 */
			if(SystemUtil.isEclipseRunTomcat()) {
				//Eclipse开发环境
				String project_path = z.sp.get("project_path");//源码路径
				File f = new File(project_path+"\\src\\main\\java\\com\\futvan\\z\\httpservices\\"+projectid+"\\"+StringUtil.firstLetterToUpper(serviceid)+"HttpService.java");
				//如果找到文件删除
				if (!f.exists()) {
					if (!f.getParentFile().exists()){
						f.getParentFile().mkdirs();
					}
					//创建文件
					f.createNewFile();

					//创建输入流
					OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
					BufferedWriter writer = new BufferedWriter(write);
					writer.write("package com.futvan.z.httpservices."+projectid+";\n");
					writer.write("import com.futvan.z.framework.core.SuperAction;\n");
					writer.write("import com.futvan.z.framework.common.bean.Result;\n");
					writer.write("import com.futvan.z.framework.common.bean.Code;\n");
					writer.write("import com.futvan.z.framework.core.z;\n");
					writer.write("import org.springframework.web.bind.annotation.RequestParam;\n");
					writer.write("import org.springframework.stereotype.Controller;\n");
					writer.write("import org.springframework.web.bind.annotation.RequestMapping;\n");
					writer.write("import org.springframework.web.bind.annotation.ResponseBody;\n");
					writer.write("import java.util.HashMap;\n");
					writer.write("/**\n");
					writer.write(" * "+bean.get("title")+"\n");
					writer.write(" */\n");
					writer.write("@Controller\n");
					writer.write("public class "+StringUtil.firstLetterToUpper(serviceid)+"HttpService extends SuperAction{\n");
					writer.write(" \n");
					writer.write("	@RequestMapping(value=\"/"+serviceid+"\")\n");
					writer.write("	public @ResponseBody Result Service(@RequestParam HashMap<String, String> bean) {\n");
					writer.write("		Result result = new Result();\n");
					writer.write(" 		Result authority = z.isServiceAuthority(bean,request);\n");
					writer.write(" 		if(Code.SUCCESS.equals(authority.getCode())){\n");
					writer.write(" 			\n");
					writer.write(" 		}else {\n");
					writer.write(" 			result = authority;\n");
					writer.write(" 		}\n");
					writer.write("		return result;\n");
					writer.write("	}\n");
					writer.write("}\n");
					writer.close();
					write.close();
				}
			}else {
				//Tomcat生产环境
				z_http_services s = z.httpservices.get(serviceid);
				CreateServicesClass(s);
			}
		}
	}


	/**
	 * 生成接口处理类并编译
	 * @param cinfo
	 */
	private void CreateServicesClass(z_http_services s) {
		//class目录
		String service_path = SystemUtil.getRunClassPath()+"com/futvan/z/httpservices/sc";

		//构建引用
		List<String> importList = new ArrayList<String>();
		importList.add("java.util.Map");
		importList.add("java.util.HashMap");
		importList.add("java.util.List");
		importList.add("java.util.ArrayList");
		importList.add("com.futvan.z.framework.core.z");
		importList.add("com.futvan.z.framework.core.SuperAction");
		importList.add("com.futvan.z.framework.common.bean.Code");
		importList.add("com.futvan.z.framework.common.bean.Result");
		importList.add("com.futvan.z.framework.common.service.CommonService");
		importList.add("org.springframework.stereotype.Controller");
		importList.add("org.springframework.web.bind.annotation.RequestParam");
		importList.add("org.springframework.web.bind.annotation.ResponseBody");
		importList.add("org.springframework.web.bind.annotation.RequestMapping");
		importList.add("org.springframework.beans.factory.annotation.Autowired");

		//定义变量
		List<JavaVariable> jvlist = new ArrayList<JavaVariable>();
		JavaVariable jv = new JavaVariable();
		jv.setPrefix("@Autowired");
		jv.setType("CommonService");
		jv.setName("commonService");
		jvlist.add(jv);

		//定义方法
		List<JavaMethod> jmlist = new ArrayList<JavaMethod>();
		JavaMethod jm = new JavaMethod();
		jm.setPrefix("	@RequestMapping(value=\"/"+s.getServiceid()+"\")");//方法前缀
		jm.setMethodType("@ResponseBody Result");//返回类型
		jm.setName("Service"); //方法名称
		jm.setCode(s.getJavainfo());
		//-----定义方法参数
		List<JavaMethodParameter> mplist = new ArrayList<JavaMethodParameter>();
		JavaMethodParameter mp = new JavaMethodParameter();
		mp.setType("@RequestParam HashMap<String, String>");
		mp.setName("bean");
		mplist.add(mp);
		jm.setParameterList(mplist);
		jmlist.add(jm);

		//创建接口文件
		JavaClass jc = new JavaClass();
		jc.setClassName(s.getServiceid()+"HttpService");//类名
		jc.setExtendsClass("SuperAction");
		jc.setTitle(s.getTitle());//标题
		jc.setPrefix("@Controller");
		jc.setPackageName("com.futvan.z.httpservices.sc");
		jc.setImportList(importList);//引用列表
		jc.setVariableList(jvlist);//成员变量列表
		jc.setMethodList(jmlist);//方法列表
		jc.setFilePath(service_path);//文件目录
		Result r = JavaCompilerUtil.CreateJava(jc);
		if(Code.SUCCESS.equals(r.getCode())) {
			//创建成功执行编译
			String java_path = jc.getFilePath()+"/"+jc.getClassName()+".java";
			
			String lib_path = SystemUtil.getRunWebAppPath()+"/lib";
			String dos = "cmd /c D:\\zjavac\\jdk\\bin\\javac -Djava.ext.dirs="+lib_path+" -encoding utf-8 "+java_path;
			SystemUtil.dos(dos);
			
			//编译完成后删除java源文件
//			FileUtil.deleteDir(new File(java_path));
			
		}else if(Code.ERROR.equals(r.getCode())){
			z.Error("生成接口处理类|出错："+r.getMsg());
		}
	}
}